package com.gt.quality.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gt.quality.config.SpringBeanUtil;
import com.gt.quality.system.entity.SysMenu;
import com.gt.quality.system.entity.SysRoleMenu;
import com.gt.quality.system.entity.vo.MenuTreeVo;
import com.gt.quality.system.entity.vo.RoleBindMenuVo;
import com.gt.quality.system.mapper.SysRoleMenuMapper;
import com.gt.quality.base.pojo.BaseLimitRequest;
import com.gt.quality.base.pojo.LayerListViewObject;
import com.gt.quality.system.service.SysMenuService;
import com.gt.quality.system.service.SysRoleMenuService;
import com.gt.quality.utils.CreateTreeUtils;
import jakarta.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 角色和菜单关联表(SysRoleMenu)表服务实现类
 *
 * @author makejava
 * @since 2026-11-25 16:30:08
 */
@Service("sysRoleMenuService")
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Resource
    private SysMenuService sysMenuService;


    /**
     * Description:  分页查询
     *
     * @param limitRequest 分页查询参数
     * @author: makeJava
     * @date: 2026-02-02 14:57:06
     * @return:com.baomidou.mybatisplus.core.metadata.IPage
     */
    @Override
    public IPage<SysRoleMenu> queryLimitPage(BaseLimitRequest<SysRoleMenu> limitRequest) {
        SysRoleMenu requestBody = limitRequest.getRequestBody();
        IPage<SysRoleMenu> page = getByPageParam(limitRequest);
        JSONObject thisObj = JSONObject.from(requestBody);
        QueryWrapper<SysRoleMenu> queryWrapper = queryWrapperBuilder(thisObj, limitRequest);
        return sysRoleMenuMapper.selectPage(page, queryWrapper);
    }

    /**
     * Description:  批量新增优化版
     *
     * @param entityList entityList
     * @author: makeJava
     * @date: 2026-02-02 19:54:59
     */
    @Override
    public Integer saveBatchByEasyBaseMapper(List<SysRoleMenu> entityList) {

        return sysRoleMenuMapper.insertBatchSomeColumn(entityList);
    }

    /**
     * 分配菜单
     *
     * @param roleId 角色Id
     */
    @Override
    public LayerListViewObject createTreeByLayer(Long roleId) {
        LayerListViewObject viewObject = new LayerListViewObject();
        List<SysMenu> list = sysMenuService.list();
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> thisMenu = sysRoleMenuMapper.selectList(wrapper);
        boolean isHavingMenu = CollUtil.isNotEmpty(thisMenu);
        List<MenuTreeVo> menuTreeVoList = new ArrayList<>(list.size());
        for (SysMenu item : list) {
            MenuTreeVo menuTreeVo = buildMenuTreeVo(item);
            menuTreeVoList.add(menuTreeVo);
        }
        List<MenuTreeVo> allMenu = CreateTreeUtils.createAnyThingTree(menuTreeVoList);
        viewObject.setNextLayer(allMenu);
        viewObject.setCurrentLayer(isHavingMenu ? thisMenu.stream().map(item->String.valueOf(item.getMenuId())).toList() : new ArrayList<>());
        return viewObject;
    }

    /**
     * 角色绑定菜单
     *
     * @param body body
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void roleBindMenu(RoleBindMenuVo body) {
        // 移除之前的绑定
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId, body.getRoleId());
        sysRoleMenuMapper.delete(wrapper);
        // 插入新的绑定
        List<Long> menuIds = body.getMenuIds();
        Optional.ofNullable(menuIds).ifPresent(item -> {
            List<SysRoleMenu> list = menuIds.stream().map(temp -> new SysRoleMenu().setMenuId(temp).setRoleId(body.getRoleId())).toList();
            sysRoleMenuMapper.insertBatchSomeColumn(list);
        });
    }




    /**
     * 构建前端返回的报文对象
     *
     * @param item         item
     * @return MenuTreeVo
     */
    private  MenuTreeVo buildMenuTreeVo(SysMenu item) {
        MenuTreeVo menuTreeVo = new MenuTreeVo();
        menuTreeVo.setIcon(item.getIcon());
        menuTreeVo.setId(item.getMenuId());
        menuTreeVo.setParentId(item.getParentId());
        menuTreeVo.setTitle(item.getMenuName());
        menuTreeVo.setSpread(true);
        menuTreeVo.setChecked(true);
        menuTreeVo.setChildren(null);
        return menuTreeVo;
    }

    /**
     * 往上传递 SqlSessionFactory
     *
     * @return SqlSessionFactory
     */
    @Override
    public SqlSessionFactory getSqlSessionFactory() {
        return super.getSqlSessionFactory();
    }

    /**
     * 往上传递 Mapper
     *
     * @return Mapper
     */
    @Override
    public Class<?> getThisMapperClass() {
        return SysRoleMenuMapper.class;
    }

    /**
     * 往上传递 Transaction
     *
     * @return Transaction
     */
    @Override
    public TransactionTemplate getSpringTx() {
        return SpringBeanUtil.getBean(TransactionTemplate.class);
    }

}


